import {
  ClientItem,
  OptionClientReq,
} from '@/api/userCenter/system/model/openapiModel'
import {
  deleteClient,
  OpenAApi,
  optionClient,
} from '@/api/userCenter/system/openapi'
import { useStore } from '@/store'
import { message } from 'ant-design-vue'
import { computed, reactive } from 'vue'
import { OptionClientDialogState } from '../types'
import { v4 as uuidv4 } from 'uuid'

const useOptionClientDialog = (searchApi: AsyncFun) => {
  const store = useStore()
  const opClientDialogState = reactive<OptionClientDialogState>({
    visiable: false,
    title: '新增OpenApi',
    formData: {
      name: '',
      clientId: '',
      clientSecret: '',
    },
  })

  const randomClient = () => {
    const randomNums = uuidv4().split('-')
    opClientDialogState.formData.clientId = randomNums.shift() || ''
    opClientDialogState.formData.clientSecret = randomNums.pop() || ''
  }

  const openAddClientDialog = () => {
    opClientDialogState.title = '新增OpenApi'
    opClientDialogState.formData.name = ''
    randomClient()

    opClientDialogState.visiable = true
  }

  const enterOpClient = async () => {
    const reqData: OptionClientReq = {
      ...opClientDialogState.formData,
    }
    await optionClient(reqData)
    message.success('操作成功')
    opClientDialogState.visiable = false
    await searchApi()
  }
  const optionClientLoading = computed(() =>
    store.getters['global/isOpLoading'](OpenAApi.OPTION_CLIENT)
  )

  const openEditClientDialog = async (client: ClientItem) => {
    opClientDialogState.title = '编辑OpenApi'
    opClientDialogState.formData.name = client.name
    opClientDialogState.formData.clientId = client.clientId
    opClientDialogState.formData.clientSecret = client.clientSecret
    opClientDialogState.visiable = true
  }

  const delClient = async (client: ClientItem) => {
    await deleteClient(client.clientId)
    message.success('删除成功')
    await searchApi()
  }
  const deleteClientLoading = computed(() =>
    store.getters['global/isOpLoading'](OpenAApi.DELETE_CLIENT)
  )

  return {
    opClientDialogState,
    openAddClientDialog,
    openEditClientDialog,
    enterOpClient,
    delClient,
    optionClientLoading,
    deleteClientLoading,
    randomClient,
  }
}

export default useOptionClientDialog
